package com.yqb.study.aop.multidatasource;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import com.yqb.study.annotation.multidatasource.DataSourceAnt;
import com.yqb.study.aop.AopOrderEnum;
import com.yqb.study.common.multidatasource.DataSourceContextHolder;
import com.yqb.study.config.multidatasource.MasterDataSourceProperties;

/**
 * 多数据源切换的aop
 */
@Aspect
@Component
@ConditionalOnProperty(prefix = "springbootstudy", name = "muti-datasource-open", havingValue = "true")
public class MultiDataSourceHandler implements Ordered {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MasterDataSourceProperties masterDataSourceProperties;      

    @Pointcut(value = "@annotation(com.yqb.study.annotation.multidatasource.DataSource)")
    private void cut() {

    }

    @Around("cut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        Signature signature = point.getSignature();
        MethodSignature methodSignature = null;
        if (!(signature instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        methodSignature = (MethodSignature) signature;

        // 拦截的实体类
        Object target = point.getTarget();
        // 设置注解的方法
        Method currentMethod = target.getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());

        DataSourceAnt datasourceAnnotion = currentMethod.getAnnotation(DataSourceAnt.class);
        if (datasourceAnnotion != null) {
        	// DataSource注解存在,设置其中的name的值作为数据源
            DataSourceContextHolder.setDataSourceType(datasourceAnnotion.dataSourceEnum().getNameEn());
            log.info("设置数据源为：" + datasourceAnnotion.dataSourceEnum().getNameEn());
        } else {
        	// DataSource注解不存在，使用"dataSourceMaster"作为数据源
            DataSourceContextHolder.setDataSourceType(masterDataSourceProperties.getName());
            log.info("设置数据源为：" + masterDataSourceProperties.getName());
        }

        try {
        	// 继续执行该方法
            return point.proceed();
        } finally {
            log.info("清空数据源信息！");
            DataSourceContextHolder.clearDataSourceType();
        }
    }

    /**
     * aop的顺序要早于spring的事务
     */
    @Override
    public int getOrder() {
        return AopOrderEnum.DATA_AOP.getNum();
    }
}
